<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/page/include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
    <link href="${ctxStatic}/layui-v2.2.45/layui/css/layui.css" rel="stylesheet"/>
    <link rel="stylesheet" href="${ctx}/css/common/common.css">
    <link href="${ctx}/css/ui/resource/selImg.css" rel="stylesheet"/>
</head>
<body>
<div class="sel-img-panel">
    <div class="upload-content">
        <form class="layui-form clearfix" action="" id="form">
            <input type="file" id="upload_input" class="u-single-file dn"
                   accept="image/gif,image/png,image/jpg,image/jpeg" multiple>
            <button class="layui-btn layui-btn-danger" id="upload_btn">选择图片</button>
            <span class="infos gray"></span>
            <div class="tags-wrap">
                <span>分类：</span>
                <div class="layui-input-inline">
                    <select id="tags_sel" name="tag" lay-verify="" lay-search>
                    </select>
                </div>
            </div>
        </form>
    </div>
    <hr class="panel-split">
    <div class="list-content">
        <ul class="img-list">
            <%--<li class="img-item" data-url="http://txztest-1252097407.image.myqcloud.com/949b34062d7e4ce685421df3889e6319/image/1529399167992.jpg" data-w="1200" data-r="1.60" data-id="41317b2281e04353bc6bc219546ee7fb">--%>
            <%--<div class="pic-box" style="background-image: url(http://txztest-1252097407.image.myqcloud.com/949b34062d7e4ce685421df3889e6319/image/1529399167992.jpg)">--%>
            <%--<div class="status-mask">--%>
            <%--<div class="upload-percent">100%</div>--%>
            <%--<div class="upload-succ"><i class="iconfont icon-check"></i><p>上传成功</p></div>--%>
            <%--</div>--%>
            <%--<div class="opts">--%>
            <%--<i class="iconfont icon-delete"></i>--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--<div class="pic-name ellipsis-1">728da9773912b31ba11816fd8c18367adbb4e1ea.jpg</div>--%>
            <%--</li>--%>
        </ul>
    </div>
</div>
<script type="text/javascript" src="${ctxStatic}/jquery/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="${ctxStatic}/layui-v2.2.45/layui/layui.js"></script>
<!-- build:js -->
<script type="text/javascript" src="${ctx}/script/common/common.js"></script>
<script type="text/javascript" src="${ctx}/script/common/util.js"></script>
<!-- endbuild -->
<script type="text/javascript" src="${ctxStatic}/cos-js-sdk-v4-master/dist/cos-js-sdk-v4.js"></script>
<script src="${ctxStatic}/exif/exif.js"></script>
<script src="${ctxStatic}/lrz/lrz.bundle.js"></script>
<script src="${ctx}/script/upload/cosUploadUtil.js"></script>
<script>
    var element, layer, layform, cosUtil, mainApp;
    var pId, // 相册id
        selTagId, // 分类id
        saveUrls = [], // 要保存的cdn路径数组
        saveResIds = [], // 要保存的文件数据库id
        uploadFiles = [], // 上传文件
        uploadFilesKeys = {}, // 上传文件key map形式
        saveImgList = []; // 保存到数据库的信息
    var isUploading = false;
    var succLength = 0;
    var selNum = 0;
    var preImgNum = 0;
    var succNum = 0; // 上传成功数
    var preImgW = 115;  // 预览压缩图片宽度
    var preImgH = 115; // 预览压缩图片高度
    var maxUploadNum = 500; // 最多一次性上传500张
    $(function () {
        layui.use(['element', 'layer', 'form'], function () {
            element = layui.element;
            layer = layui.layer;
            layform = layui.form;
            layform.on('select', function (data) {
                selTagId = data.value
            });
        });
        cosUtil = new CosUtil({
            mainFolder: '/${sessionScope.newCurrentUser.id}/image/',
            imgCompress: 1,
            onSelect: function (files) {
                var i = 0, html = '';
                var now = new Date();
                var appendHtml = function () {
                    var file = files[i];
                    if (file) {
                        var key = file.name + '_' + file.size + '_' + file.lastModified;
                        if (!uploadFilesKeys[key]) {
                            if (selNum >= maxUploadNum) {
                                util.layerMsgError('本次上传最多只能上传' + maxUploadNum + '张');
                                $('.img-list').append(html);
                                $('#upload_input').val('');
                                lazyLoad();
                                return;
                            }
                            var fId = now.getTime() + i;
                            var fileName = file.name;
                            file.id = fId;
                            file.suffix = fileName.substring(fileName.lastIndexOf('.'));
                            uploadFilesKeys[key] = file;
                            html = html + '<li class="img-item lazy-load" data-url="" data-w="" data-r="" data-key="' + key + '">' +
                                '    <div class="pic-box" style="background-image: url(${ctx}/image/loading.gif)">' +
                                '        <div class="status-mask">' +
                                '            <div class="upload-percent">0%</div>' +
                                '            <div class="handel-msg"></div>' +
                                '            <div class="upload-succ" style="display: none"><i class="iconfont icon-check"></i><p>上传成功</p></div>' +
                                '        </div>' +
                                '        <div class="opts">' +
                                '            <i class="iconfont icon-delete"></i>' +
                                '        </div>' +
                                '    </div>' +
                                '    <div class="pic-name ellipsis-1">' + file.name + '</div>' +
                                '</li>';
                            selNum++
                        }
                        i++;
                        appendHtml();
                    } else {
                        $('.img-list').append(html);
                        $('#upload_input').val('');
                        lazyLoad();
                    }
                }
                appendHtml()
            },
            onHandle: function (file, info) {
                var key = file.name + '_' + file.size + '_' + file.lastModified;
                var $item = $('.img-item[data-key="' +key+ '"]');
                $item.addClass('handel');
                $item.find('.handel-msg').text(info);
            },
            onSuccess: function (file, ret) {
                var that = this;
                var data = ret.data;
                succNum++;
                var shootDate = file.exif.DateTimeOriginal ? (Date.parse(file.exif.DateTimeOriginal.split(' ')[0].replace(/:/g, "/") + ' ' + file.exif.DateTimeOriginal.split(' ')[1])) : ''
                var saveInfo = {
                    name: file.name,
                    suffix: file.suffix,
                    createBy: '${sessionScope.newCurrentUser.id}',
                    type: mainApp.bizType,
                    path: data.resource_path,
                    width: file.width,
                    ratio: file.ratio,
                    size: file.resizeSize || file.size,
                    shootTime: shootDate,
                    cameraType: (file.exif.Make ? file.exif.Make.trim().replace(/\0/g, '') : '') + (file.exif.Model ? (' ' + file.exif.Model.trim().replace(/\0/g, '')) : '')
                };
                saveImgList.push(saveInfo)
            },
            onBatchComplete: function () {
                mainApp.saveImgs();
            },
            onProgress: function (file, ret) {
                var key = file.name + '_' + file.size + '_' + file.lastModified;
                var percent = ret < 1 ? (parseInt(ret * 100) + '%') : '100%';
                var $item = $('.img-item[data-key="' + key + '"]');
                $item.addClass('upload');
                $item.removeClass('handel');
                $item.find('.upload-percent').text(percent);
                if (ret >= 1) {
                    $item.find('.upload-percent').hide()
                    $item.find('.upload-succ').show()
                }
            },
            onFailure: function () {

            },
            onComplete: function () {

            }
        }).init();
        mainApp = {
            listContext: '',
            saveFiles: [],
            bizType: 'PHOTO',//业务类型
            successImg: [],
            selCount: 0,
            getCdnImgPath: function (path) {
                var resource_path = path, iAppid = resource_path.split('/')[1],
                    iBucket = resource_path.split('/')[2];
                var cdnPath = 'http://' + iBucket + '-' + iAppid + '.image.myqcloud.com' + resource_path.replace('/' + iAppid + '/' + iBucket, '');
                return cdnPath;
            },
            getImgTpl: function (item) {
                var resource_path = item.path, iAppid = resource_path.split('/')[1],
                    iBucket = resource_path.split('/')[2];
                var cdnPath = 'http://' + iBucket + '-' + iAppid + '.image.myqcloud.com' + resource_path.replace('/' + iAppid + '/' + iBucket, '');
                var style = (item.ratio && parseFloat(item.ratio) < 1) ? 'width: 114px' : 'height:114px';
                var tpl = '<li class="img-item" data-url="' + cdnPath + '" data-w="' + item.width + '" data-r="' + item.ratio + '" data-id="' + item.id + '">\n' +
                    '    <div class="pic-box">\n' +
                    '        <img class="pic" src="' + item.source_url + '" alt="" style="' + style + '">\n' +
                    '        <div class="status-mask">\n' +
                    '            <div class="sel-inner"><i class="iconfont icon-check"></i></div>\n' +
                    '            <div class="upload-percent">100%</div>\n' +
                    '        </div>\n' +
                    '    </div>\n' +
                    '     <div class="pic-name ellipsis-1">' + item.name + '</div>' +
                    '</li>';
                return tpl;
            },
            getProgressTpl: function (file, persent) {
                var tpl = ' <li class="upload-item" id="progress_' + file.id + '">\n' +
                    '     <div class="upload-name ellipsis-1">' + file.name + '</div>\n' +
                    '     <div class="upload-progress">\n' +
                    '         <div class="layui-progress" lay-filter="progress_' + file.id + '">\n' +
                    '             <div class="layui-progress-bar layui-bg-red" lay-percent="' + persent + '"></div>\n' +
                    '         </div>\n' +
                    '     </div>\n' +
                    ' </li>'
                return tpl;
            },
            saveToPhoto: function (url, ids) {
                //loading层
                // var loadIndex = top.layer.load(1, {
                //     shade: [0.1,'#fff'] //0.1透明度的白色背景
                // });
                txz.ajaxRequest({
                    url: '${ctx}/photo/album/addPic.do',
                    params: {
                        photosId: pId,
                        albumId: selTagId,
                        urls: url.join(','),
                        imgResourceIds: ids.join(',')
                    },
                    callBack: function (ret) {
                        if (ret.success) {
                            // top.layer.close(loadIndex);
                            if (selNum === succNum) {
                                util.layerMsgSuccess('上传成功', function () {
                                    top.location.reload();
                                });
                            }
                        } else {
                            util.layerMsg(ret.description, {}, function () {
                            });
                        }
                    }
                })
            },
            // 入库
            saveImgs: function () {
                var that = this;
                var tempImgList = JSON.parse(JSON.stringify(saveImgList));
                saveImgList = [];
                txz.ajaxRequest({
                    url: '${ctx}/file/img/api/save.do',
                    params: {
                        imgs: JSON.stringify(tempImgList)
                    },
                    callBack: function (ret) {
                        if (ret.success) {
                            for (var i = 0; i < tempImgList.length; i++) {
                                saveUrls.push(mainApp.getCdnImgPath(tempImgList[i].path))
                            }
                            succLength += tempImgList.length
                            saveResIds = saveResIds.concat(ret.data);
                            mainApp.saveToPhoto(saveUrls, saveResIds);
                            saveUrls.length = 0;
                            saveResIds.length = 0;
                            console.log('入库成功');
                        } else {
                            console.error('入库失败');
                        }
                    }
                })
            },
            init: function () {
                $('#upload_btn').on('click', function () {
                    $('#upload_input').off('change').on('change', function (e) {
                        cosUtil.opt.onSelect(e.target.files);
                        return false;
                    });
                    setTimeout(function () {
                        $('#upload_input').click();
                    }, 0);
                    return false;
                });
                $('.infos').text('${info}' || '');
            }
        };
        mainApp.init();
        pId = '${id}';
        getTags(pId);
        // 删除
        $('.img-list').on('click', '.icon-delete', function (e) {
            var $imgItem = $(this).closest('.img-item');
            var key = $imgItem.data('key');
            delete uploadFilesKeys[key];
            $imgItem.remove();
        })
        $(window).on('scroll', function () {
            lazyLoad()
        });
        lazyLoad()
    })

    function lazyLoad() {
        $('.img-item.lazy-load').each(function () {
            var seeHeight = document.documentElement.clientHeight;
            var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
            if (this.offsetTop < seeHeight + scrollTop && preImgNum < 1) {
                var $pic = $(this);
                var $picBox = $pic.find('.pic-box');
                if (!$pic.hasClass('lazy-loading')) {
                    preImgNum++;
                    $pic.addClass('lazy-loading');
                    lrz(uploadFilesKeys[$pic.data('key')], {
                        width: preImgW,
                        height: preImgH,
                        quality: 0.7,
                    }).then(function (rst) {
                        $picBox.css('background-image', 'url(' + rst.base64 + ')');
                        $pic.removeClass('lazy-loading');
                        $pic.removeClass('lazy-load');
                        preImgNum--;
                        lazyLoad();
                    });
                }
            }
        })
    }

    function upload() {
        if (!isUploading) {
            isUploading = true;
            for (var key in uploadFilesKeys) {
                uploadFiles.push(uploadFilesKeys[key])
            }
            cosUtil.uploadImg(uploadFiles);
        }
    }

    function getTags(id) {
        var tagId = '${tagId}'
        selTagId = tagId
        txz.ajaxRequest({
            url: '${ctx}/photo/album/tags.do',
            params: {
                photosId: id
            },
            callBack: function (ret) {
                if (ret.success) {
                    var tags = ret.data
                    for (var i = 0; i < tags.length; i++) {
                        $('#tags_sel').append('<option value="' + tags[i].id + '" ' + (tagId === tags[i].id ? 'selected' : '') + '>' + tags[i].name + '</option>');
                    }
                    layform && layform.render('select');
                }
            }
        })
    }

    function close() {
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        parent.layer.close(index);
    }

    function getImgs() {
        var selImgs = [];
        $('.img-item').each(function (i, item) {
            var $item = $(item)

            function getHtmlStr(item) {
                var str = '';
                if (item.width <= 100) {
                    str = '<img data-width="' + item.width + '" data-ratio="' + item.ratio + '" src="' + item.path + '" />';
                } else {
                    var _w = item.width;
                    if (item.width > 750) {
                        _w = 750;
                    }
                    str = '<p style="text-align: center"><img width="' + _w + '" data-width="' + item.width + '" data-ratio="' + item.ratio + '" src="' + item.path + '" /></p>';
                }
                return str;
            }

            var file = {
                path: $item.data('url'),
                width: $item.data('w'),
                ratio: $item.data('r'),
                id: $item.data('id')
            }
            file.htmlStr = getHtmlStr(file);
            selImgs.push(file);
        })
        return {
            tagId: selTagId,
            imgs: selImgs
        };
    }
</script>
</body>
</html>